import React, { useState, useEffect } from 'react';
import {
  Layout,
  Card,
  List,
  Button,
  Space,
  Typography,
  Input,
  Avatar,
  Tooltip,
  Empty,
  Badge
} from 'antd';
import {
  SearchOutlined,
  BookOutlined,
  HistoryOutlined,
  LinkOutlined,
  ReloadOutlined,
  GlobalOutlined
} from '@ant-design/icons';
import { TabInfo } from '../types';
import './sidepanel.less';

const { Header, Content } = Layout;
const { Title, Text } = Typography;
const { Search } = Input;

interface BookmarkItem {
  id: string;
  title: string;
  url: string;
  favicon?: string;
  dateAdded: number;
}

interface HistoryItem {
  id: string;
  title: string;
  url: string;
  visitTime: number;
  visitCount: number;
}

const SidePanel: React.FC = () => {
  const [activeTab, setActiveTab] = useState<TabInfo | null>(null);
  const [bookmarks, setBookmarks] = useState<BookmarkItem[]>([]);
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [currentView, setCurrentView] = useState<'tabs' | 'bookmarks' | 'history'>('tabs');

  useEffect(() => {
    loadTabInfo();
    loadBookmarks();
    loadHistory();
  }, []);

  const loadTabInfo = async () => {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab) {
        setActiveTab({
          id: tab.id!,
          url: tab.url!,
          title: tab.title!,
          active: true
        });
      }
    } catch (error) {
      console.error('Failed to load tab info:', error);
    }
  };

  const loadBookmarks = async () => {
    try {
      setLoading(true);
      const bookmarkTree = await chrome.bookmarks.getTree();
      const bookmarkList: BookmarkItem[] = [];
      
      const traverseBookmarks = (nodes: chrome.bookmarks.BookmarkTreeNode[]) => {
        nodes.forEach(node => {
          if (node.url) {
            bookmarkList.push({
              id: node.id,
              title: node.title,
              url: node.url,
              dateAdded: node.dateAdded || Date.now()
            });
          }
          if (node.children) {
            traverseBookmarks(node.children);
          }
        });
      };
      
      traverseBookmarks(bookmarkTree);
      setBookmarks(bookmarkList.slice(0, 20)); // 限制显示数量
    } catch (error) {
      console.error('Failed to load bookmarks:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadHistory = async () => {
    try {
      setLoading(true);
      const historyItems = await chrome.history.search({
        text: '',
        maxResults: 20
      });
      
      const historyList: HistoryItem[] = historyItems.map(item => ({
        id: item.id!,
        title: item.title!,
        url: item.url!,
        visitTime: item.lastVisitTime!,
        visitCount: item.visitCount!
      }));
      
      setHistory(historyList);
    } catch (error) {
      console.error('Failed to load history:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleOpenUrl = async (url: string) => {
    try {
      await chrome.tabs.create({ url });
    } catch (error) {
      console.error('Failed to open URL:', error);
    }
  };

  const handleBookmarkCurrentPage = async () => {
    if (!activeTab) return;
    
    try {
      await chrome.bookmarks.create({
        title: activeTab.title,
        url: activeTab.url
      });
      await loadBookmarks(); // 重新加载书签
    } catch (error) {
      console.error('Failed to bookmark page:', error);
    }
  };

  const filteredBookmarks = bookmarks.filter(
    bookmark => 
      bookmark.title.toLowerCase().includes(searchText.toLowerCase()) ||
      bookmark.url.toLowerCase().includes(searchText.toLowerCase())
  );

  const filteredHistory = history.filter(
    item => 
      item.title.toLowerCase().includes(searchText.toLowerCase()) ||
      item.url.toLowerCase().includes(searchText.toLowerCase())
  );

  const renderTabInfo = () => (
    <Card title="当前标签页" size="small">
      {activeTab ? (
        <Space direction="vertical" style={{ width: '100%' }}>
          <div className="tab-info">
            <Avatar 
              size="small" 
              icon={<GlobalOutlined />}
              src={`https://www.google.com/s2/favicons?domain=${new URL(activeTab.url).hostname}&sz=32`}
            />
            <div className="tab-details">
              <Text strong ellipsis={{ tooltip: true }}>
                {activeTab.title}
              </Text>
              <Text type="secondary" style={{ fontSize: '12px' }} ellipsis={{ tooltip: true }}>
                {activeTab.url}
              </Text>
            </div>
          </div>
          <Space>
            <Button 
              size="small" 
              icon={<BookOutlined />}
              onClick={handleBookmarkCurrentPage}
            >
              收藏
            </Button>
            <Button 
              size="small" 
              icon={<LinkOutlined />}
              onClick={() => navigator.clipboard.writeText(activeTab.url)}
            >
              复制链接
            </Button>
          </Space>
        </Space>
      ) : (
        <Empty description="无法获取标签页信息" />
      )}
    </Card>
  );

  const renderBookmarks = () => (
    <List
      dataSource={filteredBookmarks}
      loading={loading}
      locale={{ emptyText: <Empty description="暂无书签" /> }}
      renderItem={(bookmark) => (
        <List.Item
          className="bookmark-item"
          onClick={() => handleOpenUrl(bookmark.url)}
        >
          <List.Item.Meta
            avatar={
              <Avatar 
                size="small" 
                icon={<BookOutlined />}
                src={`https://www.google.com/s2/favicons?domain=${new URL(bookmark.url).hostname}&sz=32`}
              />
            }
            title={
              <Tooltip title={bookmark.title}>
                <Text ellipsis style={{ fontSize: '14px' }}>
                  {bookmark.title}
                </Text>
              </Tooltip>
            }
            description={
              <Tooltip title={bookmark.url}>
                <Text type="secondary" ellipsis style={{ fontSize: '12px' }}>
                  {bookmark.url}
                </Text>
              </Tooltip>
            }
          />
        </List.Item>
      )}
    />
  );

  const renderHistory = () => (
    <List
      dataSource={filteredHistory}
      loading={loading}
      locale={{ emptyText: <Empty description="暂无历史记录" /> }}
      renderItem={(item) => (
        <List.Item
          className="history-item"
          onClick={() => handleOpenUrl(item.url)}
        >
          <List.Item.Meta
            avatar={
              <Avatar 
                size="small" 
                icon={<HistoryOutlined />}
                src={`https://www.google.com/s2/favicons?domain=${new URL(item.url).hostname}&sz=32`}
              />
            }
            title={
              <Space>
                <Tooltip title={item.title}>
                  <Text ellipsis style={{ fontSize: '14px' }}>
                    {item.title}
                  </Text>
                </Tooltip>
                <Badge count={item.visitCount} size="small" />
              </Space>
            }
            description={
              <Space direction="vertical" size="small">
                <Tooltip title={item.url}>
                  <Text type="secondary" ellipsis style={{ fontSize: '12px' }}>
                    {item.url}
                  </Text>
                </Tooltip>
                <Text type="secondary" style={{ fontSize: '11px' }}>
                  {new Date(item.visitTime).toLocaleString()}
                </Text>
              </Space>
            }
          />
        </List.Item>
      )}
    />
  );

  return (
    <Layout className="sidepanel-layout">
      <Header className="sidepanel-header">
        <Title level={4} style={{ margin: 0, color: 'white' }}>
          侧边栏
        </Title>
        <Button
          type="text"
          icon={<ReloadOutlined />}
          style={{ color: 'white' }}
          onClick={() => {
            loadTabInfo();
            loadBookmarks();
            loadHistory();
          }}
        />
      </Header>
      
      <Content className="sidepanel-content">
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {/* 当前标签页信息 */}
          {renderTabInfo()}
          
          {/* 搜索框 */}
          <Search
            placeholder="搜索书签和历史记录"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: '100%' }}
          />
          
          {/* 导航按钮 */}
          <Space style={{ width: '100%', justifyContent: 'center' }}>
            <Button
              type={currentView === 'bookmarks' ? 'primary' : 'default'}
              icon={<BookOutlined />}
              onClick={() => setCurrentView('bookmarks')}
              size="small"
            >
              书签
            </Button>
            <Button
              type={currentView === 'history' ? 'primary' : 'default'}
              icon={<HistoryOutlined />}
              onClick={() => setCurrentView('history')}
              size="small"
            >
              历史
            </Button>
          </Space>
          
          {/* 内容区域 */}
          <div className="content-area">
            {currentView === 'bookmarks' && renderBookmarks()}
            {currentView === 'history' && renderHistory()}
          </div>
        </Space>
      </Content>
    </Layout>
  );
};

export default SidePanel;